import axios from 'axios'
import { getToken } from '@/utils/auth'

const mimeMap = {
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  zip: 'application/zip'
}

const BASE_IMAGE_PATH = process.env.VUE_APP_DOWNLOAD_BASE_PATH
const BASE_IMAGE_API = process.env.VUE_APP_DOWNLOAD_BASE_API

function downloadZip(url, filename) {
  axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: {'Authorization': 'Bearer ' + getToken()}
  }).then(res => {
    resolveBlob(res, filename, mimeMap.zip)
  })
}

function downloadImage(url, filename) {
  axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: {'Authorization': 'Bearer ' + getToken()}
  }).then(res => {
    console.log(res)
    let ext = filename.split('.').pop()
    if (ext === 'jpg' || ext === 'jpeg') {
      resolveBlob(res, filename,'image/jpeg')
    } else {
      resolveBlob(res, filename, 'image/'+ext)
    }
  })
}

function downloadExcel(url, filename) {
  const config = {
    responseType: 'blob'
  }
  return new Promise((resolve, reject) => {
    request.get(`${url}/${filename}`, config)
      .then((res) => {
        if (res && res.data && res.data.type !== 'application/json') {
          const blob = new Blob([res.data], {
            type: mimeMap.xlsx
          })
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, filename)
          } else {
            var link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = fileName
            link.click()
            // 释放内存
            window.URL.revokeObjectURL(link.href)
          }
          resolve(res)
        } else {
          Message.error({ message: '下载文件失败' })
          reject(res)
        }
      })
      .catch((res) => {
        this.$message({
          type: 'error',
          message: '下载文件失败'
        })
      })
  })
}

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
function resolveBlob(res, filename, mimeType) {
  const aLink = document.createElement('a')
  var blob = new Blob([res.data], {type: mimeType})
  // // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  // var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  // var contentDisposition = decodeURI(res.headers['content-disposition'])
  // var result = patt.exec(contentDisposition)
  // console.log(result)
  // var fileName = result[1]
  // fileName = fileName.replace(/\"/g, '')
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', filename) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
}

export default {
  downloadZip,
  downloadExcel,
  downloadImage,
  resolveBlob,
  BASE_IMAGE_PATH: BASE_IMAGE_PATH,
  BASE_IMAGE_API: BASE_IMAGE_API
}
